#----------------------------------------model
class Permission extends Backbone.Model
    defaults:
        name:''

#Permission.setup()
      
class Permissions extends Backbone.Collection
    model: Permission
    url: '/permission'
    initialize: -> @fetch()
    
class Role extends Backbone.Model
    defaults:
        name: ''
    relations: [{
        type: Backbone.HasMany,
        key: 'permissions',
        relatedModel: 'Permission'
    }]   
     
     
#Role.setup()
   
class Roles extends Backbone.Collection
    url: '/role'
    model: Role
    initialize: -> @fetch()
    
class User extends Backbone.Model
    urlRoot: '/user'
    defaults:
      name: ''
      email: ''
      role: new Role
      password:''
    relations: [{
        type: Backbone.HasOne,
        key: 'role',
        relatedModel: 'Role'
    }]  
    validation: 
        name:
            required: true
        email: 
            required: true
            pattern: 'email'
        password:
            minLength: 1
        repeatPassword:
            equalTo: 'password'
            msg: 'The passwords does not match'

#User.setup()

class Users extends Backbone.Collection
    url: '/user'
    model: User
   
#----------------------------------------------view
class PermissionItemView extends Marionette.ItemView
    template: "#permission_item_template"
    tagName: "li"
    initialize: ->
        @listenTo @model, "all", @onModelAll
        @listenTo @, "all", @onThisAll
    onThisAll: (name) => log "PermissionItemView on this event: " + name
    onModelAll: (name) => log "PermissionItemView on model event: " + name

class RoleView extends Marionette.CompositeView
    template: "#role_template"
    tagName: "div"
    itemView: PermissionItemView
    itemViewContainer: "#permissions"
    itemViewEventPrefix: "PermissionItemView"
    initialize: ->
        #@collection = new Permissions @model.get('permissions')
        @listenTo @, "all", @onThisAll
    onThisAll: (name) => log "RoleView on this event: " + name
   
class NoUserView extends Marionette.ItemView
    template: "#no-user-template"
 
    
class UserItemView extends Marionette.ItemView
    template: "#user_item_template"
    tagName: "tr"
    #itemView: RoleView
    #itemViewContainer: "#role"
    #itemViewEventPrefix: "roleView"
    emptyView: NoUserView
        
    initialize: ->
        @listenTo @model, 'change', @render
        @listenTo @model, "all", @onModelAll
        @listenTo @, "all", @onThisAll
    onThisAll: (name) => log "UserItemView on this event: " + name
    onModelAll: (name) => log "UserItemView on model event: " + name
    onCollectionAll: (name) => log "UserItemView on collection event: " + name
    events: ->
        'click a.destroy': (e) =>
            @model.destroy {wait: true}
        'click a.edit' : (e) =>
            #$.myapp.mainRegion.show new EditUserForm model: @model, collection:myapp.roles
            myapp.users_app.layout.edit_user_form(@model)
            

class UserListView extends Marionette.CompositeView
    template: "#user_table_template"
    itemView: UserItemView
    itemViewContainer: "tbody"
    itemViewEventPrefix: "userItemView"

    #model is Users
    initialize: ->
        #@listenTo @model, "all", @onModelAll
        @listenTo @collection, "all", @onCollectionAll
        @listenTo @, "all", @onThisAll
        @listenTo @collection, "request", @onModelRequest
        @listenTo @collection, "sync", @onModelSync
        @listenTo @collection, "error", @onModelError
        @listenTo @collection, "destroy", @onModelDestroied
    onThisAll: (name) => log "UserListView on this event: " + name
    onModelRequest: =>
        $(".loader").show()
    onModelSync: =>
        $(".loader").hide()
        @renderData
    onModelError: =>
        $(".loader").hide()
        @renderData
    onModelAll: (name) =>
        log "UserListView on model event: " + name
    onCollectionAll: (name) =>
        log "UserListView on collection event: " + name
        
    onModelDestroied: (model, collection, options) =>
        $(".loader").hide()
        @renderData

class RoleOptionView extends Marionette.ItemView
    template: "#role_item_template"
    tagName: "option"
        
   
# Define a View that uses our model
class EditUserForm extends Marionette.CompositeView
    tagName: "div"
    template: "#edit_user_form_template"
    itemView: RoleOptionView
    itemViewContainer: '#role_name'
    itemViewEventPrefix: "roleOptionView"
    
    events: =>
        'click #editUserButton':  (e) =>
            e.preventDefault()
            @editUser()
        'click #cancelButton': (e) =>
            e.preventDefault()
            @remove()
            
    initialize: =>
        # This hooks up the validation
        # See: http://thedersen.com/projects/backbone-validation/#using-form-model-validation/validation-binding
        Backbone.Validation.bind(this)
        
    editUser: =>
        data = $(@el).find("form").serializeObject();
        
        @model.get('role').name = data["role_name"]
        @model.set(data);
        @model.save({wait:true})

    remove: =>
        # Remove the validation binding
        # See: http://thedersen.com/projects/backbone-validation/#using-form-model-validation/unbinding
        Backbone.Validation.unbind(this)
        Backbone.View.prototype.remove.apply(this, arguments)
        
        
# Define a View that uses our model
class NewUserForm extends Marionette.CompositeView
    tagName: "div"
    template: "#new_user_form_template"
    itemView: RoleOptionView
    itemViewContainer: "#role_name"
    itemViewEventPrefix: "roleOptionView"
    events: =>
        'click #signUpButton':  (e) =>
            e.preventDefault()
            @signUp()
        'click #cancelButton': (e) =>
            e.preventDefault()
            @remove()
            
    initialize: =>
        # This hooks up the validation
        # See: http://thedersen.com/projects/backbone-validation/#using-form-model-validation/validation-binding
        Backbone.Validation.bind(this)
        
    signUp: =>
        data = $(@el).find("form").serializeObject();
        @model.get('role').set('name', data["role_name"])
        @model.set(data);
        myapp.users_app.users.create(@model, {wait: true})
        

    remove: =>
        # Remove the validation binding
        # See: http://thedersen.com/projects/backbone-validation/#using-form-model-validation/unbinding
        Backbone.Validation.unbind(this)
        Backbone.View.prototype.remove.apply(this, arguments)

class UserMainLayout extends Marionette.Layout
    template: "#user_main_layout"
    regions:
        user_form: "#new_user_form_container"
        user_table: "#user_table"
  
    events: =>
        'click #buttonNewUser': (e)=> 
            #@user_form.show new NewUserForm model: new User,collection:myapp.users_app.roles
            @new_user_form()
            
    new_user_form: ->
        editForm = new NewUserForm model: new User,collection:myapp.users_app.roles
        editForm.render()
        $('#new_user_form_container').html editForm.el
    
    edit_user_form: (user) ->
        editForm = new EditUserForm model: user,collection:myapp.users_app.roles
        editForm.render()
        $('#new_user_form_container').html editForm.el

#--------------------------------------------------controler
class UsersApp
    constructor: ->
        @users = new Users()
        @roles = new Roles()
    search: ->
        myapp.mainRegion.close()
        @layout = new UserMainLayout()
        myapp.mainRegion.show(@layout)
        @layout.user_table.show new UserListView collection: @users
        @users.fetch()
    accounts_list: =>
        myapp.mainRegion.close()
        $("#main").load "/accounts/list", (tpl) =>
            $('.myeditable').editable()
            bindModal()
            bindUserSearchForm()
            bindEditable()

#--------------------------------------------------router
class UsersAppRouter extends Backbone.Marionette.AppRouter
    appRoutes: 
        "userMain": "search"
        "accounts/list"             : "accounts_list"

   
                
myapp.addInitializer -> 
    myapp.users_app = new UsersApp()
    myapp.users_app.router = new UsersAppRouter controller: myapp.users_app

myapp.vent.trigger("routing:started")

